<template>
    <div class="content_container">
        <div class="left_container management">
            <div class="title_management">
                <h2>角色管理</h2>
            </div>
            <div class="content_management">
                <div class="select_management">
                    <div class="title">角色名称：</div>
                    <div class="content">
                        <el-input v-model="roleName" placeholder="请输入角色名称" @input="queryRolesList" clearable></el-input>
                    </div>

                    <div class="title">角色状态：</div>
                    <div class="content">
                        <el-select v-model="value" placeholder="请选择角色状态" @change="changeRoleState" clearable>
                            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                    <el-button type="success" size="small" icon="el-icon-plus" style="margin-left: 10px;"
                        @click="handleEdit($event)" v-if="btnList.includes('add')">新增角色</el-button>
                </div>
                <!-- table -->
                <div class="table_management">
                    <el-table :data="tableData" style="width: 100%" border stripe :header-cell-style="getRowClass"
                        :max-height="maxHeight" v-loading="loading">
                        <el-table-column label="创建日期" prop="createDate" align="center">
                        </el-table-column>
                        <el-table-column label="角色名" prop="roleName" align="center">
                        </el-table-column>

                        <!-- <el-table-column label="状态" align="center">
                            <template slot-scope="scope">
                                <el-switch v-model="scope.row.roleStatus" active-color="#13ce66" inactive-color="#e3e3e3"
                                    @change="changeState($event, scope.row.id)">
                                </el-switch>
                            </template>
                        </el-table-column> -->

                        <el-table-column label="操作" align="center" min-width="120px">
                            <template slot-scope="scope">
                                <el-tooltip class="item" effect="dark" content="分配权限" placement="top" v-if="btnList.includes('assginPromission')">
                                    <el-button size="mini" @click="handleEdit($event, scope.row)" icon="el-icon-thumb"
                                       ></el-button>
                                </el-tooltip>

                                <el-tooltip class="item" effect="dark" content="删除" placement="top" v-if="btnList.includes('deleteRole') && scope.row.roleName !== '超级管理员'">
                                    <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)"
                                        icon="el-icon-delete" ></el-button>
                                </el-tooltip>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
        <!-- 权限 -->
        <el-dialog title="权限分配" :visible.sync="dialogVisible" width="650px" :before-close="cancel" v-dialogDrag>
            <div class="user_name" v-if="flag">
                <div>
                    角色名：
                </div>
                <el-input placeholder="请输入角色名" v-model.trim="userName">
                </el-input>
            </div>
            <el-tabs v-model="activeName">
                <el-tab-pane label="菜单权限" name="menu">
                    <el-transfer style="text-align: left; display: flex;margin-top: 15px;" v-model="menu.bhbcvalue"
                        :data="menudata" :filter-method="filterMethod" :button-texts="['移除', '添加']" :format="{
                            noChecked: '${total}',
                            hasChecked: '${checked}/${total}'
                        }" :titles="['未拥有权限', '已拥有权限']"></el-transfer>
                </el-tab-pane>
                <el-tab-pane label="按钮权限" name="btn">
                    <el-transfer style="text-align: left; display: flex;margin-top: 15px;" v-model="btn.bhbcvalue"
                        :data="btndata" :filter-method="filterMethod" :button-texts="['移除', '添加']" :format="{
                            noChecked: '${total}',
                            hasChecked: '${checked}/${total}'
                        }" :titles="['未拥有权限', '已拥有权限']"></el-transfer>
                </el-tab-pane>
            </el-tabs>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="determine">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import mixins from './mixins';
import { throttle } from '@/utils';
import {
    getRoleListRequest,
    modifyRoleStatusRequest,
    deleteRoleRequest,
    getMenuPermissionListRequest,
    getButtonPermissionListRequest,
    saveRoleRequest
} from '@/api/management'
export default {
    roleName: 'GenecloudUiIndex',
    mixins: [mixins],
    data() {
        return {
            btnList: this.$store.state.login.buttonPermissionList,
            activeName: 'menu',
            config: null,
            tableData: [],
            options: [
                {
                    value: true,
                    label: '启用'
                },
                {
                    value: false,
                    label: '停用'
                }
            ],
            value: '',
            roleName: '',
            dialogVisible: false,
            userName: null,
            //角色编辑
            roleparams: {
                buttonIdList: [],
                id: '',
                menuIdList: [],
                roleName: ''
            },
            //菜单权限
            menu: {
                bczbh: undefined,
                bczmc: undefined,
                bhbcvalue: [],
            },
            menudata: [],
            //按钮权限
            btn: {
                bczbh: undefined,
                bczmc: undefined,
                bhbcvalue: [],
            },
            btndata: [],
            queryParams: {
                roleName: '',
                roleStatus: '',
            },
            flag: false,
        };
    },
    created() {
        this.getPermiss()
        this.getList(this.queryParams)
    },
    mounted() {

    },
    methods: {
        //获取权限列表
        async getPermiss() {
            const menu = await getMenuPermissionListRequest() 
            const btn = await getButtonPermissionListRequest() 
            this.menudata = menu.data.reduce((pre, item) => {
                pre.push({
                    key: item.id,
                    label: item.permissionName,
                })
                return pre
            }, [])
            this.btndata = btn.data.reduce((pre, item) => {
                pre.push({
                    key: item.id,
                    label: item.permissionName,
                })
                return pre
            }, [])
        },
        filterMethod(query, item) {
            return item.label.indexOf(query) > -1;
        },
        //查询角色列表
        async getList(queryParams) {
            try {
                const res = await getRoleListRequest(queryParams)
                if (res.code !== 200) return this.$message.error(res.code)
                this.tableData = res.data || []
                this.loading = false
            } catch (error) {
                this.$message.error('服务器错误，请联系管理员！')
            }
        },
        //筛选
        queryRolesList: throttle(function () {
            this.queryParams.roleName = this.roleName
            this.getList(this.queryParams)
        }, 500),
        changeRoleState(value) {
            this.queryParams.roleStatus = value
            this.getList(this.queryParams)
        },
        // 改变角色状态
        async changeState(roleStatus, id) {
            const res = await modifyRoleStatusRequest({
                id, roleStatus
            })
            if (res.code !== 200) {
                this.$message.error(res.message)
            } else {
                this.$message({
                    type: 'success',
                    message: res.message
                })
            }
            this.getList(this.queryParams)
        },
        handleEdit(event, row) {
            this.dialogVisible = true
            if (row) {
                this.flag = false
                this.roleparams.id = row.id
                this.roleparams.roleName = row.roleName
                this.btn.bhbcvalue = row.buttonPermissionList
                this.menu.bhbcvalue = row.menuPermissionList
            } else {
                this.roleparams.id = ''
                this.roleparams.roleName = ''
                this.flag = true
            }
        },
        //删除角色
        async handleDelete(id) {
            this.$confirm('您正在删除角色，是否确认操作', '警告！', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                beforeClose: async (action, instance, done) => {
                    if (action === 'confirm') {
                        const res = await deleteRoleRequest({ id })
                        if (res.code !== 200) return this.$message.error(res.message)
                        this.$message({
                            type: 'success',
                            message: res.message
                        })
                        this.getList(this.queryParams)
                    } else if (action === 'cancel') {
                        this.$message({
                            message: '取消操作',
                        })
                    }
                    done();
                }
            }).catch(() => { })

        },
        //保存
        async determine() {
            if (this.flag && !this.userName) return this.$message.error('角色名不能为空！')
            if (this.flag) {
                this.roleparams.roleName = this.userName
            }
            this.roleparams.menuIdList = this.menu.bhbcvalue
            this.roleparams.buttonIdList = this.btn.bhbcvalue
            const res = await saveRoleRequest(this.roleparams)
            if (res.code !== 200) return this.$message.error(res.message)
            this.$message({
                type: 'success',
                message: res.message
            })
            this.menu.bhbcvalue = []
            this.btn.bhbcvalue = []
            this.userName = ''
            this.activeName = 'menu'
            this.dialogVisible = false
            this.getList(this.queryParams)
        },
        //取消
        cancel() {
            this.menu.bhbcvalue = []
            this.btn.bhbcvalue = []
            this.userName = ''
            this.activeName = 'menu'
            this.dialogVisible = false
        }
    },
};
</script>

<style lang="scss" scoped>
.title_management{
    margin-left: 30px;
}
.content_management {
    margin: 0 15px;

    .table_management {
        border: 1px solid #d3ddeb;
        border-radius: 6px;

        .createDate {
            padding-top: 15px;
        }
    }

    .select_management {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        line-height: 50px;
        margin-bottom: 15px;

        ::v-deep .el-input__inner {
            height: 35px;
            line-height: 35px;
            border-radius: 4px;
        }

        .title {
            margin-left: 10px;
        }

    }
}

::v-deep .el-transfer__buttons {
    display: flex;
    align-items: center;

    .is-with-texts {
        &:first-child {
            margin: 0 5px 0 0;
        }
    }
}

::v-deep .el-tabs__nav-wrap::after {
    width: 0;
}

::v-deep .el-dialog__body {
    // margin: 0 25px 0;
    // margin: 15px;
    padding: 0 20px;
    // border: 1px solid #e9e9e9;
    // border-radius: 7px;
    // border-top: 1px solid #ccc;
    //   border-bottom: 1px solid #ccc;
    // position: relative;
    // padding: 0 0 65px;
    // height: 450px;
}

.user_name {
    display: flex;
    align-items: center;

    div {
        width: 70px;
    }

    ::v-deep .el-input__inner {
        width: 200px;
        border-radius: 4px;
        height: 35px;
        line-height: 35px;
    }
}
</style>